package common;


import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import org.junit.jupiter.api.Test;
import org.testng.Reporter;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;

public class DingDingReport {
    public static String pathname = new File("").getAbsolutePath() + "\\target\\surefire-reports\\results-json.txt";
    public static String url = "https://oapi.dingtalk.com/robot/send?access_token=177ff781ca115b374e870625191b8dc8e2556dece30f98fc2c85d365657d412b";

    public static void startSend() throws Exception {
        //String c=DingDingUtil.folatToPer((float) 5/7);
        //System.out.println(c);
        String contexts = DingDingReport.readTxtGetContext();
        ArrayList<String> mobileList = new ArrayList();
//      添加通知联系人
        mobileList.add("15940226162");
        sendMsgToGroupChat(url, false, mobileList, contexts);//  true: 通知全体人员  false: 不通知全体人员
    }


    /**
     * 通知消息发送到群聊
     *
     * @param webhook    钉钉机器人地址(配置机器人的webhook)
     * @param isAtAll    是否通知所有人
     * @param mobileList 通知具体人的手机号码列表
     * @param content    消息内容
     */
    public static void sendMsgToGroupChat(String webhook, boolean isAtAll, List<String> mobileList, String content) {
        try {
            //组装请求内容
            String reqStr = buildReqStr(content, isAtAll, mobileList);
            //推送消息(http请求)
            String result = HttpUtil.post(webhook, reqStr);
//            log.info("通知响应结果：{}",result);
            System.out.println("通知响应结果：" + result);
        } catch (Exception e) {
//            log.error("webhook通知失败",e);
            System.out.println("通知响应结果：" + e);
        }
    }


    /**
     * 组装请问报文
     *
     * @param content
     * @param isAtAll
     * @param mobileList
     * @return
     */
    private static String buildReqStr(String content, boolean isAtAll, List<String> mobileList) {
        //消息内容
        Map<String, String> contentMap = Maps.newHashMap();
        contentMap.put("content", content);

        //通知人
        Map<String, Object> atMap = Maps.newHashMap();
        //1.是否通知所有人
        atMap.put("isAtAll", isAtAll);
        //2.通知具体人的手机号码列表
        atMap.put("atMobiles", mobileList);

        Map<String, Object> reqMap = Maps.newHashMap();
        reqMap.put("msgtype", "text");
        reqMap.put("text", contentMap);
        reqMap.put("at", atMap);

        return JSON.toJSONString(reqMap);
    }

    //读取TXT的测试结果通过钉钉机器人发送钉钉消息

    /**
     * 组装发送报告文本
     *
     * @return
     * @throws Exception
     */
    public static String readTxtGetContext() throws Exception {
        Map map = new HashMap();
        map = readText(pathname);
        String features = map.get("features").toString();
        String passed = map.get("passed").toString();
        String failed = map.get("failed").toString();
        String version = map.get("version").toString();
        String scenarios = map.get("scenarios").toString();
        String threads = map.get("threads").toString();
        String failures = map.get("failures").toString();
        String ignored = map.get("ignored").toString();
        String totalTime = map.get("totalTime").toString();
        DecimalFormat df = new DecimalFormat("00.00");
        String passrate = df.format(Integer.parseInt(passed) * 100.00 / Integer.parseInt(scenarios) * 1.00);

        //获取时间
        String exectime="";
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("YYYY/MM/dd HH:mm:ss");
        exectime+=""+sdf.format(date);

        //新加钉钉机器人测试报告
        //String passRate= DingDingUtil.folatToPer((float)pass/total);
        //String url ="https://oapi.dingtalk.com/robot/send?access_token=6196580504bf64867628e6d0ed767cd40e73a8beb5138dd07c9fa0a0d3e9fdc8";
        String[] failmsg = failures.substring(1, failures.length() - 1).split(",");
        String failmsgs = "  ";
        for (int i = 0; i < failmsg.length; i++) {
            int num = i + 1;
            if (num == failmsg.length) {
                failmsgs = "\n" + failmsgs + num + " : " + failmsg[i] + "\n";
            } else {
                failmsgs = " " + failmsgs + num + " : " + failmsg[i] + "\n   ";
            }
        }

        String milkyTea = "[奶茶][流鼻血][流鼻血]";
        String context = "        [休假]    Test-Report          " +exectime+"   [休假]"+
                "\n[狗子] Feature  :      " + features +
                "\n[狗子] Scenarios:     " + scenarios +
                "\n[狗子] Passed   :      " + passed + "/" + scenarios +
                "\n[狗子] Passrate :      " + passrate + "%" +
                "\n[二哈] Failures :       http://127.0.0.1:8088/job/testDemo/\n" + "{" + failmsgs + "}";
        return context;
    }

    /**
     * 读取txt文件测试结果数据
     *
     * @param pathname
     * @return json格式测试结果数据
     * @throws Exception
     */
    public static Map readText(String pathname) throws Exception {
        //"target\\surefire-reports\\results-json.txt";
        FileReader reader = new FileReader(pathname);
        BufferedReader br = new BufferedReader(reader);
        String line = null;
        Map map = new HashMap<>();
        while ((line = br.readLine()) != null) {
            int indexa = 0;
            int indexb = 0;
            for (int i = 1; i < line.length() - 1; i++) {
                if (line.charAt(i) == '{') {
                    indexa = i;
                } else if (line.charAt(i) == '}') {
                    indexb = i;
                } else continue;
            }
            String[] strlist = (line.substring(1, indexa + 1) + line.substring(indexb, line.length() - 1)).split(",");
            String failures = line.substring(indexa, indexb + 1);
            for (int i = 0; i < strlist.length; i++) {
                if ("failures".equals(strlist[i].substring(1, 9))) {
                    map.put("failures", failures);
                } else {
                    String launch = strlist[i].split(":")[0];
                    String msg = strlist[i].split(":")[1];
                    map.put(launch.substring(1, launch.length() - 1), msg);
                }
            }
        }
        return map;
    }


    /**
     * folat数字转换为百分号格式
     *
     * @param folatNum
     * @return
     */
    public static String folatToPer(float folatNum) {
        NumberFormat numberFormat = NumberFormat.getPercentInstance();
        String per = null;
        try {
            numberFormat.setMaximumFractionDigits(2); //精确到2位
            per = numberFormat.format(folatNum);
            Reporter.log("小数点数字转百分数字符串:" + folatNum + " 转为 " + per);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return per;
    }

}
